﻿using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using ManagerGame;
using ManagerGame.Screens;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.Xna.Framework.Storage;
using System.Xml.Serialization;

namespace ManagerGame.GameSavingLogic
{
    public class GameSaver
    {

        [Serializable]
        public struct ManagerData
        {
            public Manager manager;

            public ManagerData(Manager savedManager)
            {
                this.manager = savedManager;
            }
        }

        public static void SaveManagerData(ManagerData data, StorageDevice device, string gameName)
        {
            // Create the data to save.

            ManagerData managerData = data;

            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("Storage", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string filename = gameName + ".mgr";

           // Check to see whether the save exists.
           if (container.FileExists(filename))
              // Delete it so that we can create one fresh.
              container.DeleteFile(filename);

           // Create the file.
           Stream stream = container.CreateFile(filename);

           // Convert the object to XML data and put it in the stream.
           XmlSerializer serializer = new XmlSerializer(typeof(ManagerData));
           serializer.Serialize(stream, data);

           // Close the file.
           stream.Close();

           // Dispose the container, to commit changes.
           container.Dispose();
       
        }

        public static string[] GetAListOfSavedGameFiles(StorageDevice device)
        {
           
           
            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("Storage", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string[] listOfSavedGames = container.GetFileNames("*.mgr");

            return listOfSavedGames;
        }

        public static void DeleteSavedGameFiles(StorageDevice device)
        {

            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("Storage", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string[] gameFiles = container.GetFileNames("*.mgr");
            foreach (var item in gameFiles)
            {
                container.DeleteFile(item);
            }

        }

        /// <summary>
        /// This method loads a serialized ManagerData
        /// from the StorageContainer for this game.
        /// </summary>
        /// <param name="device"></param>
        public static Manager LoadManagerData(StorageDevice device, string gameName)
        {
            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("Storage", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string filename = gameName;

            // Check to see whether the save exists.
            if (!container.FileExists(filename))
            {
                // If not, dispose of the container and return.
                container.Dispose();
                return null;
            }

            // Open the file.
            Stream stream = container.OpenFile(filename, FileMode.Open);

            // Read the data from the file.
            XmlSerializer serializer = new XmlSerializer(typeof(ManagerData));
            ManagerData data = (ManagerData)serializer.Deserialize(stream);

            // Close the file.
            stream.Close();

            // Dispose the container.
            container.Dispose();

            // Report the data to the console.
            Manager managerLoaded = data.manager;
            foreach (var item in managerLoaded.BusinessList)
            {
                int amountOfCompanies = item.Companies.Count;
                Company.UpdateCounter(item.CompanyType, amountOfCompanies);

                foreach (var company in item.Companies)
                {

                    Debug.WriteLine(company.toString());
                }
            }
            return managerLoaded;
        }
    }
}
